/*
** main.c for getBourseRates in /home/comet_a//afs/local/bourseProject
** 
** Made by alexandre comet
** Login   <comet_a@epitech.net>
** 
** Started on  Fri Nov 23 22:24:32 2012 alexandre comet
** Last update Thu Nov 29 15:20:46 2012 Ralph
*/

#include	<stdio.h>
#include	<stdlib.h>
#include	<sys/types.h>
#include	<sys/stat.h>
#include	<fcntl.h>
#include	<string.h>
#include	"my.h"

#define BUF_S	163840
#define LINE_S	2048

void		my_putchar(char c)
{
  write(1, &c, 1);
}

void		my_putstr(char *str)
{
  write(1, str, strlen(str));
}

void		my_putnbr(int nb)
{
  if (nb < 0)
    {
      my_putchar('-');
      nb = nb * -1;
    }
  if (nb > 9)
  my_putchar((nb % 10) + 48);
}

void		my_show_tab(char **tab)
{
  int		i;

  i = 0;
  while (tab[i] != NULL)
    {
      my_putstr(tab[i++]);
      my_putstr("\n");
    }
}

char		*my_strdup(char *src)
{
  char	*dest;
  int	i;

  i = 0;
  dest = NULL;
  dest = malloc(strlen(src) * sizeof(src) + 1);
  while (src[i])
    {
      dest[i] = src[i];
      i++;
    }
  dest[i] = '\0';
  return (dest);
}

void		*xmalloc(int size)
{
  void		*data;

  data = malloc(size * sizeof(data));
  if (data == NULL)
    my_putstr("Malloc failed.\n");
  return (data);
}

char		*get_next_line(const int fd)
{
  static char	buf[BUF_S];
  static int	i = BUF_S;
  static int	end = 0;
  char		*str;
  int		i2;

  str = NULL;
  i2 = 0;
  if (end == 0 && i >= (BUF_S - 1))
    {
      i = 0;
      end = read(fd, buf, BUF_S);
      buf[end] = '\0';
    }
  if (i < BUF_S && buf[i])
    {
      str = xmalloc((sizeof(str) * LINE_S));
      while (buf[i] != '\n' && buf[i] && i2 < LINE_S)
	  str[i2++] = buf[i++];
      str[i2] = '\0';
      if (buf[i])
	i++;
    }
  return (str);
}

int		istitleLine(char *line)
{
  if (istdLine(line) == 0 && strstr(line, "title") != NULL)
    return 0;
  return -1;
}

int		istdLine(char *line)
{
  if (strlen(line) > 10)
    {
      if (line[0] == '<' && line[1] == 't' && line[2] == 'd')
	return 0;
      return -1;
    }
  return -1;
}

void		get_to_wordtab(const int fd)
{
  char		*line;
  char		*temp;
  int		count = 0;

  while ((line = get_next_line(fd)))
    {
      temp = epurLine(line);
      if (istitleLine(temp) == 0)
	{
	  count++;
	  printTitle(temp);
	  printQuote(epurLine(get_next_line(fd)));
	  printVariation(epurLine(get_next_line(fd)));
	  get_next_line(fd);
	  get_next_line(fd);
	  get_next_line(fd);
	  get_next_line(fd);
//printf("volume = %s\n", epurLine(get_next_line(fd)));
	  printVolume(epurLine(get_next_line(fd)));
	  printf("\n");
	}
    }
  printf("count = %d\n", count);
}

int		xopen(char *pathname, int flags)
{
  int	fd;

  fd = open(pathname, flags);
  if (fd == -1)
    my_putstr("ERROR : Open function failed\n");
  return (fd);
}

int		main(int ac, char **av)
{
  char		*pageName;

  pageName = xmalloc(1024 * sizeof(*pageName));
  if (ac == 2) {
    pageName = downloadPage(av[1]);
    stockPrices(pageName);
  }
  else
    return (0);
  return (0);
}
